package pers.lance.mvcrest.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import pers.lance.mvcrest.db.DB;
import pers.lance.mvcrest.pojo.Book;

import java.util.List;
import java.util.UUID;

/**
 * @ Author     ：LILA3
 * @ Date       ：Created in 5:26 PM 7/25/2018
 */
@Controller
@RequestMapping(value = "/books")
public class BookController {
    private static String SUCCESS = "success";
    private static String FAIL = "fail";

    @GetMapping("/list")
    @ResponseBody
    public List<Book> list() {
        return DB.booksTable;
    }

    @PostMapping("/add")
    @ResponseBody
    public Book add(@RequestBody Book book) {
        book.setId(UUID.randomUUID().toString());
        DB.booksTable.add(book);
        return book;
    }

    @PostMapping("/delete")
    @ResponseBody
    public Book delete(@RequestBody Book book) {
        int index = -1;
        for (Book tbook : DB.booksTable) {
            index++;
            if (tbook.getId().equals(book.getId())) {
                break;
            }
        }
        if (index == -1) {
            return null;
        } else {
            DB.booksTable.remove(index);
            return book;
        }
    }

    @PostMapping("/update")
    @ResponseBody
    public String update(@RequestBody Book book) {
        int index = -1;
        for (Book tbook : DB.booksTable) {
            index++;
            if (tbook.getId().equals(book.getId())) {
                break;
            }
        }
        if (index == -1) {
            return FAIL;
        } else {
            DB.booksTable.remove(index);
            DB.booksTable.add(index, book);
            return SUCCESS;
        }
    }

    @GetMapping("/string")
    @ResponseBody
    public String String() {
        return "你好";
    }


}

